package com.pai4j.pay.config.interceptor;

import com.pai4j.common.helper.SessionHelper;
import com.pai4j.pay.config.annotation.GetAppId;
import com.pai4j.pay.config.exception.PaymentAccessAuthException;
import com.pai4j.pay.service.PaymentApiService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 解析支付接入方应用id
 */
@Slf4j
public class GetAppIdInterceptor implements HandlerInterceptor {

    @Autowired
    private PaymentApiService paymentApiService;

    /**
     * 鉴权逻辑：
     *
     * 1、从当前请求头中获取token参数
     * 2、对token实现有效性校验
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        GetAppId getAppId = method.getAnnotation(GetAppId.class);
        if (getAppId == null) {
            // 当前请求不需要校验token
            return true;
        }
        String accessToken = SessionHelper.getToken();
        if (StringUtils.isBlank(accessToken)) {
            throw new PaymentAccessAuthException("未获取到Access-Token");
        }
        Long appId = paymentApiService.getAppIdFromAccessToken(accessToken);
        if (appId == null) {
            throw new PaymentAccessAuthException("无效的Access-Token");
        }
        SessionHelper.setAppId(String.valueOf(appId));
        return true;
    }
}
